const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const path = require('path')
const fs = require('fs')
const pako = require('pako')
const axios = require('axios')
const queryString = require('querystring')
const logger = require('morgan');
const app = express()
// // 输出日志到目录
// var accessLogStream = fs.createWriteStream(path.join(__dirname, '/log/request.log'), {
//     flags: 'a',
//     encoding: 'utf8'
// });
app.use(logger('combined', {
    stream: accessLogStream
}));

const port = 3000

const EventUrl = 'http://sy.smartlink.com.cn:81/test/yiqi/buryingpoint/api/forward/appv1/event'

app.use(cors())

// app.post('/event/h5', bodyParser.urlencoded(), (req, res) => {
//     console.log('req.body', req.body);
//     res.end()
//     // base64 解密
//     const json = new Buffer(req.body.data_list, 'base64').toString()
//     // gzip 加密
//     const buffer = Buffer.from(pako.gzip(json, {
//         to: 'string'
//     }))
//     const data_list = buffer.toString('base64')
//     // 发送base64
//     axios.post(EventUrl, queryString.stringify({
//         data_list: data_list
//     }), {
//         headers: {
//             'Accept-Encoding': 'gzip',
//             'Content-Type': 'application/x-www-form-urlencoded'
//         }
//     })
//     res.end()
// })
app.post('/event/weapp', a, (req, res) => {
    // base64 解密
    const json = new Buffer(req.body.data_list, 'base64').toString()
    // gzip 加密
    const buffer = Buffer.from(pako.gzip(json, {
        to: 'string'
    }))
    const data_list = buffer.toString('base64')
    // 发送base64
    axios.post(EventUrl, queryString.stringify({
        data_list: data_list
    }), {
        headers: {
            'Accept-Encoding': 'gzip',
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    }).then(res => {
        console.log('res\n');
    }).finally(s => {
        console.log(s);
        res.end()
    })
})

function a(req, res, next) {
    const chunk = []
    req.on('data', function (buffer) {
        console.log('buffer', buffer);
        chunk.push(buffer)
    })
    let str
    req.on('end', function () {
        str = Buffer.concat(chunk).toString()

        req.body = queryString.parse(str)
        next()
    })
}

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})